#pragma once

#include <pthread.h>
#include <string>
#include <functional>
#include <unistd.h>
#include <iostream>

namespace ThreadModule
{
   
    using func_t = std::function<void(std::string)>;

   
    class Thread
    {
    public:
        Thread(func_t func, std::string name = "none-name")
            : _func(func), _name(name), _is_running(true)
        {
        }

        void Execute()
        {
            _func(_name);
        }
         
         //类成员函数形参都有this
        static void *threadroutine(void *arg)
        {
            Thread *self = static_cast<Thread*>(arg);
            self->Execute();
            return nullptr;
        }

        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, threadroutine, this);
            if (!n)
            {
                _is_running = false;
                return true;
            }
            else
            {
                return false;
            }
        }

        void Detach()
        {
            if (!_is_running)
            {
                pthread_detach(_tid);
            }
        }

        void Join()
        {
            if (!_is_running)
            {
                pthread_join(_tid, nullptr);
            }
        }

        std::string GetName()
        {
            return _name;
        }

        void Stop()
        {
            _is_running = true;
        }

        ~Thread()
        {
        }   

    private:
        pthread_t _tid;
        bool _is_running;
        func_t _func;
        std::string _name;
      
    };

} // namespace ThreadModule
